package com.wanghengzhi.kata;

import java.util.*;

/**
 * @author wanghengzhi
 * @since 2021/11/30 21:47
 */
public class Anagram {
    public Set<String> generate(String word) {
        if (word.length() == 1) {
            return Collections.singleton(word);
        }

        Set<String> result = new HashSet<>();
        for (int i = 0; i < word.length(); i++) {
            char firstChar = word.charAt(i);
            String otherChars = deleteAt(word, i);
            Set<String> anagramsOfOtherChars = generate(otherChars);
            for (String anagramsOfOtherChar : anagramsOfOtherChars) {
                result.add(firstChar + anagramsOfOtherChar);
            }
        }
        return result;
    }

    private String deleteAt(String word, int index) {
        return new StringBuilder(word).deleteCharAt(index).toString();
    }

}
